﻿using System.Security.Cryptography;
using System.Text;

namespace Super.Hmi.Utils
{
    public static class MD5Helper
    {
        /// <summary>
        /// 计算字符串的MD5值
        /// </summary>
        /// <param name="input">输入字符串</param>
        /// <returns>32位大写MD5值</returns>
        public static string MD5Encrypt(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return string.Empty;
            }
            using (var md5 = MD5.Create())
            {
                byte[] inputBytes = Encoding.UTF8.GetBytes(input);
                byte[] hashBytes = md5.ComputeHash(inputBytes);

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    sb.Append(hashBytes[i].ToString("X2")); // X2表示转换为16进制，2位
                }
                return sb.ToString();
            }
        }
        /// <summary>
        /// 验证输入内容与MD5是否匹配
        /// </summary>
        /// <param name="input">输入字符串</param>
        /// <param name="hash">要比较的MD5值</param>
        /// <returns>是否匹配</returns>
        public static bool MD5Verify(string input, string hash)
        {
            string hashOfInput = MD5Encrypt(input);
            return hashOfInput.Equals(hash, StringComparison.OrdinalIgnoreCase);
        }
    }
}
